extends MoveElement


class_name ClampElement
"""
限制在固定区域
"""


## 限制区域
@export var rect: Rect2 = Rect2(0, 0, 0, 0)


var end_point: Vector2 = Vector2.ZERO
var is_out_of_screen: bool = false


# MoveComponent就绪时触发
func on_move_ready() -> void:
    if rect.size.is_zero_approx():
        rect = move_component.wrapper.get_viewport_rect()
    end_point = move_component.wrapper.position

# 迭代加速逻辑,返回附加的速度
func yield_move(delta: float) -> Vector2:
    var p: Vector2 = move_component.wrapper.position
    if is_out_of_screen == rect.has_point(p):
        is_out_of_screen = not is_out_of_screen
        if is_out_of_screen:
            var data: Dictionary = ShapeDraw.get_first_rect_collision_normal(rect, p, (end_point - p).normalized())
            if not data.is_empty():
                var direction: Vector2 = move_component.direction.bounce(data.normal)
                move_component.turn(direction)
        else:
            end_point = p
    return Vector2.ZERO
